接下来介绍SGenome结构体。
struct SGenome
{
vector<int> vecBits;
double dFitness;
SGenome():dFitness(0){}
SGenome(const int num_bits):dFitness(0)
{
//create a random bit string
for (int i=0; i<num_bits; ++i)
{
vecBits.push_back(RandInt(0, 1)); //随机的产生一个染色体,vecBits.push_back表示往vecBits向量里塞值,RandInt(0, 1)表示塞的值要么是0,要么是1
}
}
};
定义了一个向量vecBIts,用来存储染色体中的每一位的。定义了一个dFItness,用来存储染色体的适应度函数值。
接下来就到了我们的正片环节:遗传算法类CgaBob了。
class CgaBob
{
private:
//the population of genomes
vector<SGenome> m_vecGenomes; //定义一个向量m_vecGenomes,注意这个向量的每一个元素不是int型的了,是一个SGenome结构体,没错,每个元素都是一个结构体
//size of population
int m_iPopSize; //种群中染色体数
double m_dCrossoverRate; //杂交率
double m_dMutationRate; //变异率
//how many bits per chromosome
int m_iChromoLength; //染色体的长度
//how many bits per gene
int m_iGeneLength; //基因的长度
int m_iFittestGenome; //染色体的适应度
double m_dBestFitnessScore;//最佳染色体的适应度
double m_dTotalFitnessScore;//所有染色体适应度总和
int m_iGeneration; //代数
//create an instance of the map class
CBobsMap m_BobsMap;
//we use another CBobsMap object to keep a record of
//the best route each generation as an array of visited
//cells. This is only used for display purposes.
CBobsMap m_BobsBrain;
//lets you know if the current run is in progress.
bool m_bBusy;
void Mutate(vector<int> &vecBits);
void Crossover(const vector<int> &mum, //父类
const vector<int> &dad,<span style="white-space:pre"> </span> //父类
vector<int> &baby1,<span style="white-space:pre"> </span>//子类
vector<int> &baby2);<span style="white-space:pre"> </span>//子类
SGenome& RouletteWheelSelection(); //轮盘赌
//updates the genomes fitness with the new fitness scores and calculates
//the highest fitness and the fittest member of the population.
void UpdateFitnessScores();//适应度更新
//decodes a vector of bits into a vector of directions (ints)
vector<int> Decode(const vector<int>